package com.imay.live.fragment.room;

import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.imay.base.fragment.BaseDialogFragment;
import com.imay.live.R;
import com.imay.live.helper.EventHelper;
import com.imay.live.helper.LevelHelper;
import com.imay.live.manager.AccountManager;
import com.imay.live.proto.ResultCode;
import com.imay.live.proto.helper.ProtoCallBack;
import com.imay.live.proto.helper.ProtoRequestHelper;
import com.imay.live.proto.helper.ProtoSocketFactory;
import com.imay.live.proto.room.RoomCheckAdminResp;
import com.imay.live.proto.user.UserInfoCard;
import com.imay.live.proto.user.UserInfoCardResp;
import com.imay.live.utils.GlideUtil;

/**
 * Created by jeaman on 2017/4/9.
 * 资料卡
 */

public class InfoCardFragment extends BaseDialogFragment implements View.OnClickListener{
    private static final String BUNDLE_NAME_ROOM_ID = "roomId";
    private static final String BUNDLE_NAME_USER_INFO = "user_info";
    private static final String BUNDLE_NAME_OWNER = "owner";    //自己是否主播
    private static final String BUNDLE_NAME_ANCHOR = "anchor";  //对方是否主播
    private static final String BUNDLE_NAME_SELF = "self";

    private ImageView mAvatarIv;
    private ImageView mVipIv;
    private TextView mNickTv;
    private TextView mFamilyTv;
    private TextView mLiveLevelTv;
    private TextView mUserLevelTv;
    private TextView mRoomIdTv;
    private TextView mIntroTv;
    private TextView mFansTv;
    private TextView mFollowerTv;
    private View mAdminMenuView;
    private View mUserMenuView;
    private View mActionGiftView;
    private View mActionView;
    private TextView mFollowAnchorTv;
    private TextView mFollowTv;
    private ImageView mFollowAnchorIv;
    private ImageView mFollowIv;

    private long mRoomId;
    private boolean mAdmin;
    private UserInfoCard mUserInfoCard;
    private boolean mFollow;
    private boolean isSelf,isAnchor,isOwner;

    public static InfoCardFragment newInstance(long roomId, UserInfoCard userInfoCard, boolean self, boolean owner, boolean anchor) {
        InfoCardFragment fragment = new InfoCardFragment();
        Bundle bundle = new Bundle();
        bundle.putLong(BUNDLE_NAME_ROOM_ID, roomId);
        bundle.putSerializable(BUNDLE_NAME_USER_INFO, userInfoCard);
        bundle.putBoolean(BUNDLE_NAME_SELF, self);
        bundle.putBoolean(BUNDLE_NAME_ANCHOR, anchor);
        bundle.putBoolean(BUNDLE_NAME_OWNER, owner);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_info_card;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        Bundle bundle = getArguments();

        mAdminMenuView = $(R.id.info_card_iv_menu_admin);
        mUserMenuView = $(R.id.info_card_iv_menu_user);
        mAvatarIv = $(R.id.info_card_iv_avatar);
        mNickTv = $(R.id.info_card_tv_nick);
        mFamilyTv = $(R.id.info_card_tv_family);
        mLiveLevelTv = $(R.id.info_card_tv_live_level);
        mUserLevelTv = $(R.id.info_card_tv_user_level);
        mRoomIdTv = $(R.id.info_card_tv_rid);
        mIntroTv = $(R.id.info_card_tv_intro);
        mFansTv = $(R.id.info_card_tv_fans);
        mFollowerTv = $(R.id.info_card_tv_follower);
        mFollowTv = $(R.id.info_card_tv_follow);
        mFollowAnchorTv = $(R.id.info_card_tv_follow_gift);
        mFollowIv = $(R.id.info_card_iv_follow);
        mFollowAnchorIv = $(R.id.info_card_iv_follow_gift);
        mActionGiftView = $(R.id.info_card_ll_action_gift);
        mActionView = $(R.id.info_card_ll_action);
        mVipIv = $(R.id.info_card_iv_vip);

        initListener();

        mRoomId = bundle.getLong(BUNDLE_NAME_ROOM_ID);
        isSelf = bundle.getBoolean(BUNDLE_NAME_SELF);
        isAnchor = bundle.getBoolean(BUNDLE_NAME_ANCHOR);
        isOwner = bundle.getBoolean(BUNDLE_NAME_OWNER);
        setUserData((UserInfoCard) bundle.getSerializable(BUNDLE_NAME_USER_INFO));
        setViewMode(isSelf, isOwner, isAnchor);
        requestUserData();
        if (!isOwner && !isSelf && !isAnchor) {    //非主播，判断是否管理员
            checkAdmin();
        }
    }

    @Override
    protected int getWindowAnimations() {
        return R.style.dialog_from_bottom;
    }

    @Override
    protected int getGravity() {
        return Gravity.BOTTOM;
    }

    @Override
    protected int getHeight() {
        return WindowManager.LayoutParams.WRAP_CONTENT;
    };

    @Override
    protected boolean isMatchParent() {
        return true;
    }

    @Override
    public boolean isOutsideTouchable() {
        return true;
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        ProtoRequestHelper.cancelRequest(this.hashCode());
        super.onDismiss(dialog);
    }

    private void initListener() {
        $(R.id.info_card_iv_close).setOnClickListener(this);
        $(R.id.info_card_iv_menu_admin).setOnClickListener(this);
        $(R.id.info_card_iv_menu_user).setOnClickListener(this);
        $(R.id.info_card_ll_at).setOnClickListener(this);
        $(R.id.info_card_ll_follow).setOnClickListener(this);
        $(R.id.info_card_ll_at_gift).setOnClickListener(this);
        $(R.id.info_card_ll_gift_gift).setOnClickListener(this);
        $(R.id.info_card_ll_follow_gift).setOnClickListener(this);
        mAvatarIv.setOnClickListener(this);
    }

    private void showUserData() {
        GlideUtil.loadCircleBorderImage(mAvatarIv ,mUserInfoCard.imgHead, R.dimen.size_3dp, R.color.line_ff, R.mipmap.pnl_00_head108);
        mNickTv.setText(mUserInfoCard.nick);
        mLiveLevelTv.setBackgroundResource(LevelHelper.getLiveLevelResId(mUserInfoCard.LiveLv));
        mUserLevelTv.setBackgroundResource(LevelHelper.getUserLevelResId(mUserInfoCard.UserLv));
        mLiveLevelTv.setText(String.valueOf(mUserInfoCard.LiveLv));
        mUserLevelTv.setText(String.valueOf(mUserInfoCard.UserLv));
        mRoomIdTv.setText(getString(R.string.live_room_roomid, mUserInfoCard.roomId));
        mFollowerTv.setText(String.valueOf(mUserInfoCard.follow));
        mFansTv.setText(String.valueOf(mUserInfoCard.follower));
        if (!TextUtils.isEmpty(mUserInfoCard.intro)) {
            mIntroTv.setVisibility(View.VISIBLE);
            mIntroTv.setText(mUserInfoCard.intro);
        }
        setFollowUser(mUserInfoCard.myFollow);
        int vipRes = LevelHelper.getVIPIcon(mUserInfoCard.OfficialVip, mUserInfoCard.LargeVipStatus);
        mVipIv.setVisibility(vipRes == 0 ? View.GONE : View.VISIBLE);
        mVipIv.setImageResource(vipRes);
        if (!TextUtils.isEmpty(mUserInfoCard.designation)) {
            mFamilyTv.setText(mUserInfoCard.designation);
            mFamilyTv.setVisibility(View.VISIBLE);
        }
    }

    //刷新用户信息
    private void requestUserData() {
        ProtoRequestHelper.task(ProtoSocketFactory.requestUserInfo(mUserInfoCard.uid)).setTag(this.hashCode()).request(new ProtoCallBack() {
            @Override
            public void onRequestSuccess(String command, String data) {
                    UserInfoCardResp resp = JSON.parseObject(data, UserInfoCardResp.class);
                    if (resp.result == ResultCode.CodeSuccess) {
                        if (resp.info != null) {
                            if (isAdded()) {
                                setUserData(resp.info);
                            }
                        }
                    }
            }

            @Override
            public void onRequestError(String command, int code, String message) {

            }
        });
    }

    private void setUserData(UserInfoCard userInfoCard) {
        mUserInfoCard = userInfoCard;
        showUserData();
    }

    public void setViewMode(boolean self, boolean owner, boolean anchor) {
        //自己的资料卡需要隐藏部分界面
        if (self) {
            mActionView.setVisibility(View.GONE);
            mActionGiftView.setVisibility(View.GONE);
            mAdminMenuView.setVisibility(View.GONE);
        } else {
            setAdminMode(owner);
            //如果自己是主播，或者对方是主播显示礼物按钮
            mActionView.setVisibility(owner || anchor ? View.GONE : View.VISIBLE);
            mActionGiftView.setVisibility(owner || anchor ? View.VISIBLE : View.GONE);
        }
    }

    private void setAdminMode(boolean admin) {
        if (isAdded() && !isDetached()) {
            if (admin) {
                mAdminMenuView.setVisibility(View.VISIBLE);
                mUserMenuView.setVisibility(View.GONE);
            } else {
                mAdminMenuView.setVisibility(View.GONE);
                mUserMenuView.setVisibility(View.VISIBLE);
            }
        }
    }

    private void setFollowUser(boolean follow) {
        mFollow = follow;
        if (isAdded() && !isDetached()) {
            mFollowTv.setText(mFollow ? getString(R.string.button_un_follow) : getString(R.string.button_follow) );
            mFollowAnchorTv.setText(mFollow ? getString(R.string.button_un_follow) : getString(R.string.button_follow) );
            mFollowIv.setVisibility(mFollow ? View.GONE : View.VISIBLE);
            mFollowAnchorIv.setVisibility(mFollow ? View.GONE : View.VISIBLE);
        }
    }

    private void checkAdmin() {
        //判断自己是否管理员
        ProtoRequestHelper.task(ProtoSocketFactory.requestCheckAdmin(mRoomId, AccountManager.getInstance().getUid())).setTag(this.hashCode()).request(new ProtoCallBack() {
            @Override
            public void onRequestSuccess(String command, String data) {
                RoomCheckAdminResp resp = JSON.parseObject(data, RoomCheckAdminResp.class);
                if (resp.result == ResultCode.CodeSuccess) {
                    if (resp.isAdmin) {
                        if (!mAdmin) {  //自己是管理员且对方不是管理员才显示管理菜单
                            setAdminMode(true);
                        }
                    }
                }
            }

            @Override
            public void onRequestError(String command, int code, String message) {

            }
        });

        //判断对方是否管理员
        ProtoRequestHelper.task(ProtoSocketFactory.requestCheckAdmin(mRoomId, mUserInfoCard.uid)).setTag(this.hashCode()).request(new ProtoCallBack() {
            @Override
            public void onRequestSuccess(String command, String data) {
                RoomCheckAdminResp resp = JSON.parseObject(data, RoomCheckAdminResp.class);
                if (resp.result == ResultCode.CodeSuccess) {
                    if (resp.isAdmin) { //对方是管理员，显示举报菜单
                        mAdmin = true;
                        setAdminMode(false);
                    }
                }
            }

            @Override
            public void onRequestError(String command, int code, String message) {

            }
        });
    }

    //TODO 关注统一使用后台请求，成功后通过消息通知UI
    private void toggleFollow() {
        if (mFollow) {  //取消关注
            ProtoRequestHelper.task(ProtoSocketFactory.requestUnFollowUser(mUserInfoCard.uid)).setTag(this.hashCode()).request(new ProtoCallBack() {
                @Override
                public void onRequestSuccess(String command, String data) {
                    setFollowUser(false);
                    EventHelper.postUnFollowUser(mUserInfoCard.uid);
                }

                @Override
                public void onRequestError(String command, int code, String message) {

                }
            });
        } else {
            //关注
            ProtoRequestHelper.task(ProtoSocketFactory.requestFollowUser(mUserInfoCard.uid)).setTag(this.hashCode()).request(new ProtoCallBack() {
                @Override
                public void onRequestSuccess(String command, String data) {
                    setFollowUser(true);
                    EventHelper.postFollowUser(mUserInfoCard.uid);
                }

                @Override
                public void onRequestError(String command, int code, String message) {

                }
            });
        }
    }

    @Override
    public void onClick(View v) {
        OnInfoCardClickListener listener = null;
        if (getActivity() instanceof OnInfoCardClickListener) {
            listener = (OnInfoCardClickListener) getActivity();
        }
        switch (v.getId()) {
            case R.id.info_card_iv_close:
                dismiss();
                break;
            case R.id.info_card_iv_menu_admin:
                dismiss();
                if (listener != null) {
                    listener.onAdminMenuClick(mUserInfoCard);
                }
                break;
            case R.id.info_card_iv_menu_user:
                dismiss();
                if (listener != null) {
                    listener.onUserMenuClick(mUserInfoCard);
                }
                break;
            case R.id.info_card_ll_at:
            case R.id.info_card_ll_at_gift:
                dismiss();
                if (listener != null) {
                    listener.onAtClick(mUserInfoCard);
                }
                break;
            case R.id.info_card_ll_gift_gift:
                dismiss();
                if (listener != null) {
                    listener.onGiftClick(mUserInfoCard);
                }
                break;
            case R.id.info_card_ll_follow:
            case R.id.info_card_ll_follow_gift:
                toggleFollow();
                break;
            case R.id.info_card_iv_avatar:
                if (!isOwner&&listener != null) {
                    listener.onUserHeadClick(mUserInfoCard);
                    dismiss();
                }
                break;
        }
    }

    public interface OnInfoCardClickListener {
        void onAtClick(UserInfoCard userInfoCard);
        void onGiftClick(UserInfoCard userInfoCard);
        void onAdminMenuClick(UserInfoCard userInfoCard);
        void onUserMenuClick(UserInfoCard userInfoCard);
        void onUserHeadClick(UserInfoCard userInfoCard);
    }
}
